-- UIShare
-- Created by chengb Nov/3/2015
-- 分享界面

UIShare = class("UIShare", function()
    return cc.Layer:create();
end);

function UIShare.create(shareWay, shareType, title, desc, args)
    return UIShare.new(shareWay, shareType, title, desc, args);
end

-- 构造函数
function UIShare:ctor(shareWay, shareType, title, desc, args)
    self:setName("UIShare");

    local node = cc.CSLoader:createNode("layout/share/FBShare.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.BONUS_NOTIFY_ZORDER + 1);

    trace("UIShare", "shareWay = %d, shareTpe = %d, title = %s, desc = %s, args = %o",
        shareWay, shareType, title, desc, args);

    self.shareWay  = shareWay;
    self.shareType = shareType;
    self.title     = title;
    self.desc      = desc;
    args = args or {};

    if shareWay == SHARE_WAY_FACEBOOK then
        -- facebook分享
        args["url"]      = getLocStr("fb_share_url");
        args["imageUrl"] = FormulaM.invoke("GET_FB_SHARE_IMAGE_URL", shareType);
    elseif shareWay == SHARE_WAY_LINE then
        -- line分享
        args["url"] = FormulaM.invoke("GET_LINE_SHARE_URL", shareType);
    elseif shareWay == SHARE_WAY_WECHAT_SESSION then
        -- 微信分享
        args["url"] = ShareM.getCNShareUrl();
    elseif shareWay == SHARE_WAY_WECHAT_FRIENDS then
        -- 朋友圈分享
        args["url"] = ShareM.getCNShareUrl();
    elseif shareWay == SHARE_WAY_WEIBO then
        -- 微博分享
        args["url"] = ShareM.getCNShareUrl();
    else
        error("暂不支持的分享途径：" .. tostring(shareWay));
    end

    self.args = args;

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIShare:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 重绘
function UIShare:redraw()
    -- 标题
    local titleLabel = findChildByName(self.node, "CT/title");
    TextStyleM.setTitleStyle(titleLabel);
    titleLabel:setString(self.title);

    -- 描述
    local descLabel = findChildByName(self.node, "CT/desc");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    descLabel = applyString(descLabel, self.desc);

    -- 奖励
    local bonusList = ShareM.calcShareBonus(self.shareType);
    self:initBonusItem(bonusList);

    local imgBtnIcon = findChildByName(self.node, "CT/btn_ok/icon");
    if self.shareWay == SHARE_WAY_FACEBOOK then
        -- facebook
        imgBtnIcon:loadTexture("images/ui/channel/fb_share_01.png");
    elseif self.shareWay == SHARE_WAY_LINE then
        -- line
        imgBtnIcon:loadTexture("images/ui/channel/line_share_01.png");
    elseif self.shareWay == SHARE_WAY_WECHAT_SESSION then
        -- 微信
        imgBtnIcon:loadTexture("images/ui/channel/weixin_share_01.png");
    elseif self.shareWay == SHARE_WAY_WECHAT_FRIENDS then
        -- 朋友圈
        imgBtnIcon:loadTexture("images/ui/channel/friends_share_01.png");
    elseif self.shareWay == SHARE_WAY_WEIBO then
        -- 微博
        imgBtnIcon:loadTexture("images/ui/channel/weibo_share_01.png");
    end

    -- 自适应所有组件
    local bg = findChildByName(self.node, "CT/bg_frame");
    local bg1 = findChildByName(self.node, "CT/bg1");
    local bg2 = findChildByName(self.node, "CT/bg2");
    local bonusPanel = findChildByName(self.node, "CT/bonus_panel");
    local okBtn = findChildByName(self.node, "CT/btn_ok");
    local descLabel = findChildByName(self.node, "CT/desc");

    AlignM.adaptLayout(bg, AlignM.BG_SIZE_NORMAL,
        { titleLabel, descLabel, bonusPanel, okBtn}, { 35, });
end

-- 初始化奖励
function UIShare:initBonusItem(bonusList)
    local parentNode = findChildByName(self.node, "CT/bonus_panel/bonus_node");

    -- 先清空
    parentNode:removeAllChildren();

    local item = cc.CSLoader:createNode("layout/equip/equip_item.csb");
    item = replaceNodeWithWidget(item);

    local descLabel = findChildByName(self.node, "CT/desc");

    local itemWidth = 100;
    local gap = 20;
    local widget = ccui.Widget:create();
    local totalWidth = #bonusList * (itemWidth + gap);
    local itemsStr = "";
    local totalCount = #bonusList;
    local msg = "";

    for i = 1, totalCount do
        local bonus = bonusList[i];

        local child = item:clone();
        child:setPositionX((i - 1) * (itemWidth + gap));

        -- 图标
        local name;
        local iconPath;
        local scale = 0.88;
        local offsetY = 0;
        local icon = findChildByName(child, "btn");
        local tip = getLocStr("get_res_tip");
        if bonus[1] == 1 then
            -- 是道具， 获取道具图标
            iconPath = getItemIconPath(ItemM.query(bonus[2], "icon"));

            if ItemM.query(bonus[2], "type") == ITEM_TYPE_SPELL then
                local itemBg = findChildByName(child, "bg");
                itemBg:setVisible(false);
            end
        elseif bonus[1] == 2 then
            -- 属性
            iconPath = getLargeAttribIconPath(FieldsM.query(bonus[2], "icon"));
        end
        icon:loadTexture(iconPath)
        icon:setScale(scale);
        icon:setPositionY(icon:getPositionY() + offsetY);

        -- 个数
        local countLabel = findChildByName(child, "count");
        TextStyleM.setTextStyle(countLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, -3);
        countLabel:setString(tostring(bonus[3]));
        countLabel:setVisible(true);
        countLabel:setPositionX(0);
        countLabel:setPositionY(-itemWidth/2 + 5);

        widget:addChild(child);
    end

    widget:setPositionX(- totalWidth / 2 + (itemWidth + gap) / 2);
    parentNode:addChild(widget);
end

-- 注册点击事件
function UIShare:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");

            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIShare");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册分享按钮点击事件
    local btnOk = findChildByName(self.node, "CT/btn_ok");
    local fbImg = findChildByName(btnOk, "icon");
    local function onBonusClick(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            if self.shareWay == SHARE_WAY_FACEBOOK then
                -- facebook分享
                fbImg:loadTexture("images/ui/channel/fb_share_02.png");
            elseif self.shareWay == SHARE_WAY_LINE then
                -- line分享
                fbImg:loadTexture("images/ui/channel/line_share_02.png");
            elseif self.shareWay == SHARE_WAY_WECHAT_SESSION then
                -- 微信分享
                fbImg:loadTexture("images/ui/channel/weixin_share_02.png");
            elseif self.shareWay == SHARE_WAY_WECHAT_FRIENDS then
                -- 朋友圈分享
                fbImg:loadTexture("images/ui/channel/friends_share_02.png");
            elseif self.shareWay == SHARE_WAY_WEIBO then
                -- 微博分享
                fbImg:loadTexture("images/ui/channel/weibo_share_02.png");
            end
        elseif eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            local args = self.args;
            if self.shareWay == SHARE_WAY_FACEBOOK then
                -- 显示facebook分享对话框
                fbImg:loadTexture("images/ui/channel/fb_share_01.png");
                showFBShareDialog(args.title, args.desc, args.url, args.imageUrl, self.shareType)
            elseif self.shareWay == SHARE_WAY_LINE then
                -- 打开line分享链接
                fbImg:loadTexture("images/ui/channel/line_share_01.png");
                if not ShareM.lineShare(args.url) then
                    -- 失败了，这里可能是网络问题
                    return;
                end
                local function callback()
                    EventMgr.fire(event.LINE_SHARE_SUCC, { ["shareType"] = self.shareType });
                    closeFormByName("UIShare");
                end
                performWithDelay(self, callback, 1);
            elseif self.shareWay == SHARE_WAY_WECHAT_SESSION then
                -- 微信分享
                fbImg:loadTexture("images/ui/channel/weixin_share_01.png");
                if self.shareType == SHARE_TYPE_SLIME then
                    -- 如果是冈布奥分享，需要生成屏幕快照
                    self:wechatShareSlimeImage(WECHAT_SCENE_SESSION);
                elseif self.shareType == SHARE_TYPE_AIRSHIP then
                    -- 如果是飞艇分享，需要生成屏幕快照
                    self:wechatShareAirshipImage(WECHAT_SCENE_SESSION);
                else
                    ShareM.wechatShare(WECHAT_SCENE_SESSION, self.shareType, { ["desc"] = args.desc, ["url"] = args.url, });
                    closeFormByName("UIShare");
                end
            elseif self.shareWay == SHARE_WAY_WECHAT_FRIENDS then
                -- 朋友圈分享
                fbImg:loadTexture("images/ui/channel/friends_share_01.png");
                if self.shareType == SHARE_TYPE_SLIME then
                    -- 如果是冈布奥分享，需要生成屏幕快照
                    self:wechatShareSlimeImage(WECHAT_SCENE_FRIENDS);
                elseif self.shareType == SHARE_TYPE_AIRSHIP then
                    -- 如果是飞艇分享，需要生成屏幕快照
                    self:wechatShareAirshipImage(WECHAT_SCENE_FRIENDS);
                else
                    ShareM.wechatShare(WECHAT_SCENE_FRIENDS, self.shareType, { ["desc"] = args.desc, ["url"] = args.url, });
                    closeFormByName("UIShare");
                end
            elseif self.shareWay == SHARE_WAY_WEIBO then
                -- 微博分享
                fbImg:loadTexture("images/ui/channel/weibo_share_01.png");
                self:weiboShareImage();
            end
        end
    end
    btnOk:addTouchEventListener(onBonusClick);
    TextStyleM.setTextStyle(btnOk, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnOk:setTitleText(getLocStr("btn_text_share"));
end

-- 微信分享冈布奥图片
function UIShare:wechatShareSlimeImage(sceneType)
    -- 先生成屏幕快照
    local imageName = WECHAT_SHARE_SLIME_IMAGE;
    local classId = self.args.classId;
    createGainPetSnapshot(imageName, classId);

    local function callback()
        ShareM.wechatShare(sceneType, SHARE_TYPE_SLIME, { ["desc"] = self.args.desc, ["image"] = imageName,});
        closeFormByName("UIShare");
    end

    performWithDelay(self, callback, 0.01);
end

-- 微信分享飞艇图片
function UIShare:wechatShareAirshipImage(sceneType)
    -- 先生成屏幕快照
    local imageName = WECHAT_SHARE_AIRSHIP_IMAGE;
    local classId = self.args.classId;
    createGainAirshipSnapshot(imageName, classId);

    local function callback()
        ShareM.wechatShare(sceneType, SHARE_TYPE_AIRSHIP, { ["desc"] = self.args.desc, ["image"] = imageName,});
        closeFormByName("UIShare");
    end

    performWithDelay(self, callback, 0.01);
end

-- 微博分享图片
function UIShare:weiboShareImage()
    local text = self.args.desc  .. tostring(ShareM.getCNShareUrl());
    local imageName;
    local isShowWating = false;

    if self.sharetType == SHARE_TYPE_GAME then
        -- 设置界面分享游戏
        imageName = WEIBO_SHARE_GAME_IMAGE;
        createGameLogoSnapshot(imageName);
    elseif self.shareType == SHARE_TYPE_DUNGEON then
        -- 迷宫分享
        -- 随机选取一张图片地址
        imageName = ShareM.fetchWeiboShareDungeonImage();

        -- 这里需要到网站链接上下载图片，时间相对较长，因此需要弹一个等待界面
        isShowWating = true;
    elseif self.shareType == SHARE_TYPE_SLIME then
        -- 冈布奥分享
        local classId = self.args.classId;
        imageName = WEIBO_SHARE_SLIME_IMAGE;
        createGainPetSnapshot(imageName, classId);
    elseif self.shareType == SHARE_TYPE_AIRSHIP then
        -- 飞艇分享
        local classId = self.args.classId;
        imageName = WEIBO_SHARE_AIRSHIP_IMAGE;
        createGainAirshipSnapshot(imageName, classId);
    end

    if not imageName then
        trace("UIShare", "生成屏幕快照失败了。");
        return;
    end

    local function callback()
        if ShareM.weiboShare(self.shareType, imageName, text) then
            if isShowWating then
                -- 显示等待中，超时关闭
                local timeout = 15;
                showCommunicatingForm(getLocStr("waiting"), nil, nil, timeout);
            end

            closeFormByName("UIShare");
        end
    end
    performWithDelay(self, callback, 0.01);
end

-- 注册事件处理回调函数
function UIShare:registerEventCallback()
    -- 注册分享成功的事件
    EventMgr.register("UIShare", event.FB_SHARE_SUCC, function(args)
        -- 关闭当前界面
        closeFormByName("UIShare");
    end);

    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIShare 界面析构清理");
            EventMgr.removeAll("UIShare");
        end
    end);

end








